package api;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.mysql.jdbc.Connection;
import lombok.SneakyThrows;
import model.UserInfo;
import util.AppVar;
import util.DBUtils;
import util.ResultUtils;
import util.SessionUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.PreparedStatement;

@WebServlet("/delart")
public class DelArticleServlet extends HttpServlet {
    @SneakyThrows
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.从前端的得到参数
        Integer aid=null;
        int data=0;
        String msg="未知错误";
        //验证用户登录状态并验证归属人（自己只能删除自己的文章）
        UserInfo userInfo= SessionUtils.getLoginUser(req);
        if(userInfo!=null){
            try {
                aid = Integer.valueOf(req.getParameter("aid"));
            }catch (Exception e){
            }
            if(aid!=null && aid>0){//参数有效
                //删除文章
                Connection connection= DBUtils.getConnection();
                String sql="delete from article where aid=? and uid=?";
                PreparedStatement statement = connection.prepareStatement(sql);
                statement.setInt(1,aid);
                statement.setInt(2,userInfo.getUid());
                data=statement.executeUpdate();
                msg="";
                DBUtils.close(null,statement,connection);
            }else{
                msg="参数错误";
            }
        }else{
            msg="请先登录!";
        }

        resp.setContentType(AppVar.RESPONSE_CONTENTTYPE_JSON);
        resp.getWriter().println(JSONUtil.toJsonStr(ResultUtils.toResult(200,data,msg)));
    }
}
